import pymysql.cursors
import logging
import uuid
import json
import system_setup
from flask import request,jsonify
from uirls import time_uirls
from data_analysis import data_subscription
from device_info import update_device_currentState
from configparser import ConfigParser
from threading import Thread,Lock
from uirls import web_socket
import base64

# 读取配置文件
conf = ConfigParser()
conf.read("setting.ini",encoding='utf-8')
# 互斥锁
mutex = Lock()
# log日志
logging.basicConfig(level = logging.DEBUG,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# 数据库连接
def mysql():
    mydb = pymysql.connect(
        host=conf.get("mysql_settings","host"),
        port=int(conf.get("mysql_settings","port")),
        user=conf.get("mysql_settings","user"),
        password=conf.get("mysql_settings","password"),
        database='data_info',
        cursorclass=pymysql.cursors.DictCursor
    )
    return mydb
# 报警日志添加
def add(jsons):
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        if jsons.__contains__('number'):
            sql = "SELECT * from device_info.device_info where number = '" + jsons['number'] + "'"
            cursor.execute(sql)
            device = cursor.fetchone()
            if device is None: return jsonify(code=1,msg="设备不存在")
            number = jsons['number']
            device_classify = device['device_classify']
            device_type = device['device_type']
            alarm_type = jsons['alarmType'] if jsons['alarmType'] is not None else ""
            alarm_type_name = jsons['alarmTypeName']
            content = jsons['content']
            alarm_time = jsons['alarmTime']
            position = device['position']
            alarm_phone = device['alarm_phone']
            device_class = device['device_class']
            device_name = device['name']
            url = ""
            if jsons.__contains__('url'):
                url = jsons['url']
            id = str(uuid.uuid4())
            sql = "insert into device_alarm_log (id,number,device_classify,device_type,alarm_type,alarm_type_name,content,alarm_time,position,alarm_phone,device_class,device_name,image_path) values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" \
                  %(id,number,device_classify,device_type,alarm_type,alarm_type_name,content,alarm_time,position,alarm_phone,device_class,device_name,url)
            insert = cursor.execute(sql)
            mydb.commit()
            jsonParam = {"number": number,"time": alarm_time,"currentState": "2"}
            # 更新设备状态
            update_device_currentState(jsonParam)
            # 第三方消息订阅
            jsons['position'] = position
            jsons['name'] = device_name
            jsons['gatewayNumber'] = conf.get("gateway_box","gatewayNumber")
            # ws
            web_socket.send(str(jsons).replace("'",'"'))
            # 短信、语音推送
            data_subscription.dataPush(jsons)
            if jsons.__contains__('url'):
                url = jsons['url']
                ip,path = url.split('upload')
                path = '/mnt/work/www/upload'+path
                f = open(path, "rb")
                #读取文件的内容转换为base64编码
                ls_f = str(base64.b64encode(f.read()),'utf-8')
                jsons['base64images'] = ls_f
                f.close()
            # 数据订阅
            data_subscription.data(jsons)
            # 第三方消息订阅mqtt
            data_subscription.mqtt_data(jsons)
        else:
            return jsonify(code=1,msg="缺少必要参数number")
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close() # 关闭连接
    return jsonify(
        msg = "success",
        code = 0
    )
# 获取今日、当月报警量
def day_month_alarm_count():
    response = system_setup.getDecodeToken(request.headers.get("Authorization","")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg = token['msg'],
            code = 1
        )
    elif token['code'] == 401:
        return jsonify(
            msg = token['msg'],
            code = token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        sql = "select COUNT(alarm_time) as count from device_alarm_log where TO_DAYS(alarm_time) = TO_DAYS(now())"
        cursor.execute(sql)
        dayCount = cursor.fetchone()
        sql = "SELECT COUNT(alarm_time) as count FROM device_alarm_log WHERE DATE_FORMAT(alarm_time, '%Y%m' ) = DATE_FORMAT(CURDATE( ) , '%Y%m' )"
        cursor.execute(sql)
        monthCount = cursor.fetchone()
        json_data = {}
        json_data['dayAlarmCount'] = dayCount['count']
        json_data['monthAlarmCount'] = monthCount['count']
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close() # 关闭连接
    return jsonify(
        msg="success",
        code=0,
        data=json_data
    )
# 告警统计（折线图）
def all_alarm_data_count():
    response = system_setup.getDecodeToken(request.headers.get("Authorization","")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg = token['msg'],
            code = 1
        )
    elif token['code'] == 401:
        return jsonify(
            msg = token['msg'],
            code = token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.args
        # 开始时间
        startTime = jsons['startTime']
        # 结束时间
        endTime = jsons['endTime']
        deviceClassify = "AND device_classify = '" + jsons.get("deviceClassify") + "'" if jsons.get("deviceClassify") is not None else ""
        deviceClass = "AND device_class = '" + jsons.get("deviceClass") + "'" if jsons.get("deviceClass") is not None else ""
        sql = "SELECT alarm_time FROM device_alarm_log WHERE 1=1 "+deviceClassify+deviceClass+" AND alarm_time BETWEEN '"+startTime+"' AND '"+endTime+"' ORDER BY alarm_time DESC"
        cursor.execute(sql)
        cur_data = cursor.fetchall()
        return_data = []
        if jsons.__contains__('type'):
            if jsons['type'] == '天':
                hours = time_uirls.getHour(endTime[11:13])
                for hour in hours:
                    count = 0
                    json_data = {}
                    for data in cur_data:
                        date_time = str(data['alarm_time'])
                        if date_time[11:13] == hour:
                            count = count+1
                    json_data[hour] = count
                    return_data.append(json_data)
            elif jsons['type'] == '周':
                days = time_uirls.getDay(7,endTime)
                for day in days:
                    count = 0
                    json_data = {}
                    for data in cur_data:
                        date_time = str(data['alarm_time'])
                        if date_time[5:10] == day:
                            count = count+1
                    json_data[day] = count
                    return_data.append(json_data)
            elif jsons['type'] == '月':
                days = time_uirls.getDay(30,endTime)
                for day in days:
                    count = 0
                    json_data = {}
                    for data in cur_data:
                        date_time = str(data['alarm_time'])
                        if date_time[5:10] == day:
                            count = count+1
                    json_data[day] = count
                    return_data.append(json_data)
            elif jsons['type'] == '年':
                months = time_uirls.getMonths(endTime)
                for month in months:
                    count = 0
                    json_data = {}
                    for data in cur_data:
                        date_time = str(data['alarm_time'])
                        if date_time[:7] == month:
                            count = count+1
                    json_data[month] = count
                    return_data.append(json_data)
        else:
            startTime1,startTime2 = startTime.split(' ')
            endTime1,endTime2 = endTime.split(' ')
            if startTime1 == endTime1:
                hours = time_uirls.getHour(endTime[11:13])
                for hour in hours:
                    count = 0
                    json_data = {}
                    for data in cur_data:
                        date_time = str(data['alarm_time'])
                        if date_time[11:13] == hour:
                            count = count+1
                    json_data[hour] = count
                    return_data.append(json_data)
            else:
                days = time_uirls.getDays(startTime1,endTime1)
                for day in days:
                    count = 0
                    json_data = {}
                    for data in cur_data:
                        date_time = str(data['alarm_time'])
                        if date_time[:10] == day:
                            count = count+1
                    json_data[day] = count
                    return_data.append(json_data)
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()
    return jsonify(
        msg="success",
        code=0,
        data=return_data
    )
# 最新告警列表（3条）
def new_alarm_data_list():
    response = system_setup.getDecodeToken(request.headers.get("Authorization","")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg = token['msg'],
            code = 1
        )
    elif token['code'] == 401:
        return jsonify(
            msg = token['msg'],
            code = token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.args
        deviceClassify = "AND device_classify = '" + jsons.get("deviceClassify") + "'" if jsons.get("deviceClassify") is not None else ""
        deviceClass = "AND device_class = '" + jsons.get("deviceClass") + "'" if jsons.get("deviceClass") is not None else ""
        sql = "SELECT id,alarm_type_name,alarm_time,is_handle,image_path FROM device_alarm_log where 1=1 " +deviceClassify+deviceClass+" ORDER BY alarm_time DESC LIMIT 5"
        #mutex.acquire()
        cursor.execute(sql)
        #mutex.release()
        cur_data = cursor.fetchall()
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()
    return jsonify(
        msg="success",
        code=0,
        data=cur_data
    )
# 告警排名（前十）
def alarm_ranking():
    response = system_setup.getDecodeToken(request.headers.get("Authorization","")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg = token['msg'],
            code = 1
        )
    elif token['code'] == 401:
        return jsonify(
            msg = token['msg'],
            code = token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        sql = "SELECT  device_name,COUNT(alarm_type) AS count FROM device_alarm_log GROUP BY number ORDER BY count DESC LIMIT 10"
        #mutex.acquire()
        cursor.execute(sql)
        #mutex.release()
        cur_data = cursor.fetchall()
    except Exception as e:
        logging.debug("%sException+++"%e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()
    return jsonify(
        msg="success",
        code=0,
        data=cur_data
    )
# 今日报警数据统计
def today_alarm_count():
    response = system_setup.getDecodeToken(request.headers.get("Authorization","")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg = token['msg'],
            code = 1
        )
    elif token['code'] == 401:
        return jsonify(
            msg = token['msg'],
            code = token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.args
        if jsons.__contains__("deviceClass"):
            # 返回数据
            json_data = {}
            # 今日报警总数
            allCount = 0
            if jsons['deviceClass'] == '2002':#建筑消防用水
                sql = "SELECT device_type,COUNT(device_type) as count FROM device_alarm_log  where device_class = '"+jsons['deviceClass']+"'AND TO_DAYS(alarm_time) = TO_DAYS(now()) GROUP BY device_type"
                cursor.execute(sql)
                cur_data = cursor.fetchall()
                # 室内消火栓
                indoorFireHydrant = 0
                # 室外消火栓
                outdoorFireHydrant = 0
                # 末端试水
                endWaterTest = 0
                # 消防水箱
                fireWaterTank = 0
                for data in cur_data:
                    if data['device_type'] == '1004':
                        fireWaterTank = fireWaterTank+data['count']
                    elif data['device_type'] == '1005':
                        endWaterTest = endWaterTest+data['count']
                    elif data['device_type'] == '1006':
                        outdoorFireHydrant = outdoorFireHydrant+data['count']
                    elif data['device_type'] == '1007':
                        indoorFireHydrant = indoorFireHydrant+data['count']
                # 今日报警总数
                allCount = indoorFireHydrant+outdoorFireHydrant+endWaterTest+fireWaterTank
                json_data['indoorFireHydrant'] = indoorFireHydrant
                json_data['outdoorFireHydrant'] = outdoorFireHydrant
                json_data['endWaterTest'] = endWaterTest
                json_data['fireWaterTank'] = fireWaterTank
                json_data['allCount'] = allCount
            elif jsons['deviceClass'] == '2001':#用户传输装置
                # 火警
                fireAlarm = 0
                # 故障
                fault = 0
                # 系统事件
                systemEvent = 0
                json_data['fireAlarm'] = fireAlarm
                json_data['fault'] = fault
                json_data['systemEvent'] = systemEvent
                json_data['allCount'] = allCount
            elif jsons['deviceClass'] == '2003':#智慧烟感
                # 烟雾报警
                smokeAlarm = 0
                # 信号异常
                abnormalSignal = 0
                json_data['smokeAlarm'] = smokeAlarm
                json_data['abnormalSignal'] = abnormalSignal
                json_data['allCount'] = allCount
            elif jsons['deviceClass'] == '2004':#电气火灾
                # 电压
                voltage = 0
                # 电流
                electricCurrent = 0
                # 温度
                temperature = 0
                # 漏电流
                leakageCurrent = 0
                json_data['voltage'] = voltage
                json_data['electricCurrent'] = electricCurrent
                json_data['temperature'] = temperature
                json_data['leakageCurrent'] = leakageCurrent
                json_data['allCount'] = allCount
            elif jsons['deviceClass'] == '2005':#可燃气体
                # 可燃气体
                combustibleGas = 0
                json_data['combustibleGas'] = combustibleGas
                json_data['allCount'] = allCount
            elif jsons['deviceClass'] == '2006':#消防水泵
                # 电压故障
                voltageFault = 0
                json_data['voltageFault'] = voltageFault
                json_data['allCount'] = allCount
            elif jsons['deviceClass'] == '1001':#视频设备
                sql = "SELECT alarm_type,COUNT(alarm_type) as count FROM device_alarm_log  where device_class = '"+jsons['deviceClass']+"'AND TO_DAYS(alarm_time) = TO_DAYS(now()) GROUP BY alarm_type"
                cursor.execute(sql)
                cur_data = cursor.fetchall()
                # # 火焰报警
                # flameAlarm = 0
                # # 消防通道
                # fireEngineAccess = 0
                # # 脱岗离岗
                # OffDuty = 0
                # for data in cur_data:
                #     if data['alarm_type'] == '001e7548-8735-4b31-b30b-c9361a62c973':
                #         OffDuty = OffDuty+data['count']
                # json_data['flameAlarm'] = flameAlarm
                # json_data['fireEngineAccess'] = fireEngineAccess
                # json_data['OffDuty'] = OffDuty
                for data in cur_data:
                    json_data[data['alarm_type']] = data['count']
                    allCount = allCount+data['count']
                json_data['allCount'] = allCount
        else:return jsonify(code=1,msg="缺少必要参数deviceClass")
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()
    return jsonify(
        msg="success",
        code=0,
        data=json_data
    )
# 报警日志分页列表
def alarmListPage():
    response = system_setup.getDecodeToken(request.headers.get("Authorization","")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.args
        if jsons.__contains__('page') and jsons.__contains__('limit'):
            page = jsons.get("page")
            limit = jsons.get("limit")
            number = " AND number like '%" + jsons.get("number") + "%'" if jsons.get("number") is not None else ""
            device_name = " AND device_name like '%" + jsons.get("device_name") + "%'" if jsons.get("device_name") is not None else ""
            isHandle = " AND is_handle = '" + jsons.get("isHandle") + "'" if jsons.get("isHandle") is not None else ""
            deviceClassify = " AND device_classify = '" + jsons.get("deviceClassify") + "'" if jsons.get("deviceClassify") is not None else ""
            start_time = " AND alarm_time >= '" + jsons.get("start_time") + "'" if jsons.get("start_time") is not None else ""
            end_time = " AND alarm_time <= '" + jsons.get("end_time") + "'" if jsons.get("end_time") is not None else ""
            deviceClass = " AND device_class = '" + jsons.get("deviceClass") + "'" if jsons.get("deviceClass") is not None else ""
            alarm_type_name = " AND alarm_type_name = '" + jsons.get("alarm_type_name") + "'" if jsons.get("alarm_type_name") is not None else ""
            sql = "SELECT * from device_alarm_log where 1=1 " + number + device_name + isHandle + deviceClassify + deviceClass + start_time + end_time +alarm_type_name+ " order by alarm_time desc"
            cursor.execute(sql)
            cur_data = cursor.fetchall()
            items = []
            for item in cur_data[int(limit)*(int(page)-1):int(limit)*int(page)]:
                temp = {}
                temp['id'] = item['id']
                temp['number'] = item['number']
                temp['device_classify'] = item['device_classify']
                temp['device_type'] = item['device_type']
                temp['alarm_type'] = item['alarm_type']
                temp['alarm_type_name'] = item['alarm_type_name']
                temp['content'] = item['content']
                temp['alarm_time'] = item['alarm_time']
                temp['is_handle'] = item['is_handle']
                temp['alarm_phone'] = item['alarm_phone']
                temp['handletime'] = item['handle_time']
                temp['handle_person'] = item['handle_person']
                temp['infoconfirm'] = item['infoconfirm']
                temp['handle_remark'] = item['handle_remark']
                temp['device_class'] = item['device_class']
                temp['device_name'] = item['device_name']
                temp['position'] = item['position']
                temp['image_path'] = item['image_path']
                items.append(temp)
            rlt_data = {}
            num = len(cur_data)
            rlt_data["totalSize"] = num
            rlt_data["pages"] = num // int(limit) + 1
            rlt_data["pageSize"] = limit
            rlt_data["Items"] = items
            rlt_data["currentPage"] = page
            rlt_data["currentSize"] = limit
            if int(page)==rlt_data["pages"]:
                rlt_data["currentSize"] = num % int(limit)
        else:
            return jsonify(code=1,msg="缺少必要参数page、limit")
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close() # 关闭连接
    return jsonify(
        msg="success",
        code=0,
        data=rlt_data
    )


# 报警日志删除
def alarm_log_del():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.json
        if jsons.__contains__('id'):
            sql = "DELETE FROM device_alarm_log WHERE id = '" + jsons['id'] + "'"
            cursor.execute(sql)
            mydb.commit()
        else:
            return jsonify(code=1, msg="缺少必要参数id")
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 再关闭数据库连接
    return jsonify(
        msg="success",
        code=0
    )


# 报警日志详情
def alarmDetails():
    response = system_setup.getDecodeToken(request.headers.get("Authorization","")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.args
        if jsons.__contains__('id'):
            sql = "select * from device_alarm_log where id='"+jsons.get("id")+"'"
            cursor.execute(sql)
            device_alarm_log = cursor.fetchone()
        else:
            return jsonify(code=1,msg="缺少必要参数id")
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close() # 关闭连接
    return jsonify(
        msg="success",
        code=0,
        data=device_alarm_log
    )
# 报警处置
def alarmHandle():
    response = system_setup.getDecodeToken(request.headers.get("Authorization","")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.json
        if jsons.__contains__('id') and jsons.__contains__('handlePerson') and jsons.__contains__('infoConfirm') and jsons.__contains__('batchHandle') and jsons.__contains__('handleTime'):
            id = jsons['id']
            sql = "SELECT * from device_alarm_log where id = '" + id + "'"
            cursor.execute(sql)
            device_alarm_log = cursor.fetchone()
            if device_alarm_log is None: return jsonify(code=1,msg="日志不存在")
            handlePerson = jsons['handlePerson']
            infoConfirm = str(jsons['infoConfirm'])
            batchHandle = jsons['batchHandle']
            handleTime = jsons['handleTime']
            handleRemark = ''
            if jsons.__contains__('handleRemark'):handleRemark = jsons['handleRemark']
            sql = ''
            if batchHandle:
                sql = "UPDATE device_alarm_log SET is_handle =1,handle_time ='"+handleTime+"',handle_person ='"+handlePerson+"',infoconfirm ="+infoConfirm+",handle_remark ='"+handleRemark+"' WHERE is_handle = 0 and number = '" + device_alarm_log['number'] + "'"
            else:
                sql = "UPDATE device_alarm_log SET is_handle =1,handle_time ='"+handleTime+"',handle_person ='"+handlePerson+"',infoconfirm ="+infoConfirm+",handle_remark ='"+handleRemark+"' WHERE id = '" + id + "'"
            insert = cursor.execute(sql)
            mydb.commit()
        else:
            return jsonify(code=1,msg="缺少必要参数id、handlePerson、infoConfirm、batchHandle、handleTime")
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close() # 关闭连接
    return jsonify(
        msg="success",
        code=0
    )


# 报警日志分页列表
def device_alarm_log_list():
    response = system_setup.getDecodeToken(request.headers.get("Authorization","")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.json
        if jsons.__contains__('id') and jsons.__contains__('handlePerson') and jsons.__contains__('infoConfirm') and jsons.__contains__('batchHandle') and jsons.__contains__('handleTime'):
            id = jsons['id']
            sql = "SELECT * from device_alarm_log where id = '" + id + "'"
            cursor.execute(sql)
            device_alarm_log = cursor.fetchone()
            if device_alarm_log is None: return jsonify(code=1,msg="日志不存在")
            handlePerson = jsons['handlePerson']
            infoConfirm = str(jsons['infoConfirm'])
            batchHandle = jsons['batchHandle']
            handleTime = jsons['handleTime']
            handleRemark = ''
            if jsons.__contains__('handleRemark'):handleRemark = jsons['handleRemark']
            sql = ''
            if batchHandle:
                sql = "UPDATE device_alarm_log SET is_handle =1,handle_time ='"+handleTime+"',handle_person ='"+handlePerson+"',infoconfirm ="+infoConfirm+",handle_remark ='"+handleRemark+"' WHERE is_handle = 0 and number = '" + device_alarm_log['number'] + "'"
            else:
                sql = "UPDATE device_alarm_log SET is_handle =1,handle_time ='"+handleTime+"',handle_person ='"+handlePerson+"',infoconfirm ="+infoConfirm+",handle_remark ='"+handleRemark+"' WHERE id = '" + id + "'"
            insert = cursor.execute(sql)
            mydb.commit()
        else:
            return jsonify(code=1,msg="缺少必要参数id、handlePerson、infoConfirm、batchHandle、handleTime")
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close() # 关闭连接
    return jsonify(
        msg="success",
        code=0
    )



def test():
    json_s = {"type":"查询","mess":"7777777"}
    print(str(json_s))
    web_socket.send(str(json_s).replace("'",'"'))
    return jsonify(
        msg="success",
        code=0
    )
